<template>
  <div class="task-manage page-container">
    <el-form class="query-form"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
      size="small"
      label-width="">
      <el-form-item class="big-query" label="关键词"
        prop="name">
        <el-input v-model="queryParams.name"
          placeholder="请输入关键词"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
          @clear="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary"
          size="small"
          @click="handleQuery">搜索</el-button>
        <el-button size="small"
          @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="operate-wrap">
      <el-button type="primary" @click.stop="openTaskDialog()"  size="small" icon="el-icon-plus">新增</el-button>
    </div>
    <el-table v-loading="loading" :data="taskList">
      <el-table-column label="奖品ID"  width="100" prop="id" />
      <el-table-column label="奖品名" prop="name" width="200" />
      <el-table-column label="奖品总数量" width="100" prop="total" />
      <el-table-column label="剩余数量" width="100" prop="remain" />
      <el-table-column label="预警" min-width="80" prop="weight">
        <template slot-scope="scope">
          <el-switch
            v-if="scope.row.setting && scope.row.setting.alarm"
            :value="scope.row.setting.alarm.enable"
            :active-value="1"
            :inactive-value="0"
            @change="handleEnableChange($event,scope.row)">
          </el-switch>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="奖品描述" min-width="120" prop="desc" />
      <el-table-column label="奖品状态" min-width="120" prop="status">
        <template slot-scope="scope">
          <span>{{scope.row.status | filterRewardStatus}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="150">
        <template slot-scope="scope">
          <!-- <el-button type="text" size="small">查看</el-button> -->
          <el-button type="text" size="small" @click.stop="openTaskDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click.stop="updateRewardStatus(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-wrap">
      <pagination v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getTableList" />
    </div>
    <el-dialog
      class="add-task-dialog"
      :title="form.id ? '编辑奖品':'新增奖品'"
      :visible.sync="dialogVisible"
      width="660px"
      top="10vh"
      :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="奖品类型" prop="type" >
          <el-select v-model="form.type" placeholder="请选择任务类型" :disabled="!!form.id" @change="changeType">
            <el-option v-for="(value,key) in rewardTypes" :key="key" :label="value" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="奖品名称" prop="name">
          <el-input v-model.trim="form.name" :maxLength="30"></el-input>
        </el-form-item>
        <!-- 奖品兑换码区域 -->
        <el-form-item label="奖品兑换码" prop="code_file" :rules="form.id ?{}:{required: true, message: '请上传文件', trigger: 'change'}" v-if="['external_code','markup_code'].includes(form.type)">
          <el-upload
            class="upload-demo"
            action="#"
            accept="text/plain"
            :limit="1"
            :show-file-list="true"
            :file-list="form.fileList"
            :http-request="onUpload"
            :before-upload="beforeUpload"
            :on-remove="onFileRemove">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">1.文件必须是txt格式</div>
              <div slot="tip" class="el-upload__tip">2.每行排列一条数据，请勿添加其他注释</div>
              <div slot="tip" class="el-upload__tip">3.不能存在重复码</div>
              <div slot="tip" class="el-upload__tip">4.大小不超过100M</div>
          </el-upload>

        </el-form-item>
        <!-- 奖品兑换码区域 -->
        <el-form-item label="奖品数量" prop="total" v-if="['external_code','markup_code'].includes(form.type) && form.total">
          <span>{{form.total}}</span>
        </el-form-item>
        <el-row :gutter="10" style="padding-left:60px;" v-if="['external_code','markup_code'].includes(form.type)">
          <el-col :span="5">
              <el-form-item label="预警" label-width="60px" prop="setting.alarm.enable">
                  <el-switch v-model="form.setting.alarm.enable" :inactive-value="0" :active-value="1"></el-switch>
              </el-form-item>
          </el-col>
          <template v-if="form.setting.alarm.enable == 1">
              <el-col :span="15">
                  <el-form-item label="" label-width="0px" prop="setting.alarm.least">
                      <div class="inner-item">奖品低于<el-input-number v-model="form.setting.alarm.least" controls-position="right" :min="1" :max="10"></el-input-number>个预警</div>
                  </el-form-item>
              </el-col>
          </template>
        </el-row>
        <el-form-item label="预警机器人key" v-if="['external_code','markup_code'].includes(form.type)" prop="setting.alarm.robot" :rules="form.setting.alarm.enable == 0 ?{}:{required: true, message: '请填写预警机器人key', trigger: 'blur'}">
          <el-input v-model="form.setting.alarm.robot"></el-input>
        </el-form-item>

        <el-form-item label="数量" prop="setting.grant.quantity" v-if="['charge'].includes(form.type)" >
          <el-input-number v-model="form.setting.grant.quantity" controls-position="right" ></el-input-number>
          <el-select v-model="form.setting.grant.unit" placeholder="请选择" style="width:180px;margin-left:10px;" @change="unitSelectChange">
            <el-option v-for="item in chargeUnitList" :key="item.unit_id" :label="item.internal_name" :value="item.unit_id"></el-option>
          </el-select>
        </el-form-item>
        <template v-if="['right_pkg'].includes(form.type)">
          <el-form-item label="权益包" prop="setting.grant.pkg_id" >
            <el-select v-model="form.setting.grant.pkg_id" placeholder="请选择权益包">
              <el-option v-for="(item) in pkgList" :key="item.package_id" :label="item.name" :value="item.package_id"></el-option>
            </el-select>
          </el-form-item>
        </template>
        <template v-if="['right_pkg', 'charge'].includes(form.type)">
          <el-form-item label="期限" prop="setting.grant.duration">
            <el-select v-model="form.setting.grant.duration" placeholder="请选择">
              <el-option v-for="(item, index) in memberTimeOptions" :key="index" :label="item[1]" :value="item[0]" />
            </el-select>
          </el-form-item>
        </template>
        <!-- <el-form-item label="单位" prop="setting.grant.quantity" v-if="['charge'].includes(form.type)">
          <el-input-number v-model="form.setting.grant.quantity" controls-position="right" ></el-input-number>
        </el-form-item> -->
        <el-form-item label="发放分数" prop="total" v-if="['charge','right_pkg'].includes(form.type)">
          <el-input-number v-model="form.total" controls-position="right" ></el-input-number>
        </el-form-item>
        <template v-if="['charge'].includes(form.type)">
          <el-form-item label="奖品有效期" key="expireDate_charge">
            <el-date-picker
                v-model="form.expireDate"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                >
            </el-date-picker>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="奖品有效期" prop="expireDate" key="expireDate">
            <el-date-picker
                v-model="form.expireDate"
                type="daterange"
                value-format="yyyy-MM-dd HH:mm:ss"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                >
            </el-date-picker>
          </el-form-item>
        </template>

        <el-form-item label="奖品描述" prop="desc">
          <el-input v-model="form.desc" type="textarea" :autosize="{minRows: 2, maxRows: 6}"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addReward">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { listRightPackage } from '@/api/rights/package'
import { addReward, getRewardList, updateReward } from '@/api/reward-manage'
import { uploadApi } from '@/api/rights/rights'
import { getChargeUnit } from '@/api/system'
import { getMemberValidTime } from '@/constants/constant'
export default {
  data () {
    return {
      pkgList: [],
      chargeUnitList: [],
      memberTimeOptions: [],
      queryParams: {
        page: 1,
        page_size: 10,
        name: ''
      },
      rewardTypes: {
        'external_code': '兑换码',
        'charge': '计费资源类型',
        'right_pkg': '权益包'
        // 'markup_code': '定价兑换码'
      },
      total: 0,
      taskList: [],
      currentPage: 1,
      dialogVisible: false,
      loading: false,
      form: {
        name: '',
        type: 'external_code',
        code_file: '',
        fileList: [],
        setting: {
          alarm: {
            enable: 0,
            least: 5,
            robot: ''
          },
          grant: {
            quantity: 0,
            unit: '',
            unit_name: '',
            pkg_id: null,
            duration: null
          }
        },
        expireDate: [],
        total: 0,
        desc: ''
      },
      rules: {
        name: [
          { required: true, message: '请填写奖品名称', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择奖品类型', trigger: 'change' }
        ],
        expireDate: [
          { required: true, message: '请选择奖品有效期', trigger: 'blur' }
        ],
        'setting.grant.pkg_id': [
          { required: true, message: '请选择权益包', trigger: 'change' }
        ],
        'setting.grant.duration': [
          { required: true, message: '期限不得为空', trigger: 'change' }
        ]
      }
    }
  },
  filters: {
    filterRewardStatus (status) {
      const statusDictMap = {
        'valid': '有效',
        'expire': '过期',
        'not_start': '未开始',
        'deleted': '删除'
      }
      return statusDictMap[status] || '-'
    }
  },
  methods: {
    changeType (value) {
      this.reset()
      this.form.type = value
    },
    unitSelectChange (value) {
      this.form.setting.grant.unit_name = this.$options.filters.translateToName(value, this.chargeUnitList, 'unit_id', 'name')
    },
    handleEnableChange (val, { setting, id }) {
      if (!setting) {
        return
      }
      const { page: pageIndex, page_size: pageSize } = this.queryParams
      setting.alarm.enable = val
      updateReward({ id, setting: JSON.stringify(setting) }).then(() => {
        this.queryParams.page = this.getCurrentPage({ total: this.total, pageSize, pageIndex })
        this.getTableList()
        this.msgSuccess(`${val === 1 ? '开启预警' : '关闭预警'}成功`)
      })
    },
    getPackageRightList () {
      listRightPackage({ page: 1, page_size: 100, status: 1 }).then(res => {
        this.pkgList = res.data.list || []
      })
    },
    openTaskDialog (row) {
      getChargeUnit().then(res => {
        // this.chargeUnitList = res.data.list.filter(item => item.unit_id === 'draw')
        this.chargeUnitList = res.data.list
      })
      this.dialogVisible = true
      this.$nextTick(() => {
        this.editRow = null
        this.reset()
        if (row) {
          this.editRow = row
          const { setting, start_at, stop_at, ...other } = row
          const tempForm = { ...other,
            ...{
              // expireDate: [new Date(start_at * 1000), new Date(stop_at * 1000)],
              fileList: []
            } }

          if (start_at && stop_at) {
            tempForm['expireDate'] = [new Date(start_at * 1000), new Date(stop_at * 1000)]
          } else {
            tempForm['expireDate'] = []
          }
          Object.keys(tempForm).forEach(key => {
            this.form[key] = tempForm[key]
          })
          if (setting) {
            this.form.setting = JSON.parse(JSON.stringify(setting))
          }
        } else {
          this.form.id = ''
          this.form.total = 0
        }
      })
    },
    // 获取列表数据
    getTableList () {
      this.loading = true
      getRewardList(this.queryParams).then(res => {
        this.taskList = res.data.list.map(item => {
          if (item.setting) {
            try {
              item.setting = JSON.parse(item.setting)
            } catch (e) {
              console.log(e, '--error--')
            }
          }
          return item
        })
        this.total = res.data.count || 0
      }).finally(() => {
        this.loading = false
      })
    },
    // 点击搜索
    handleQuery () {
      this.queryParams.page = 1
      this.getTableList()
    },
    // 重置
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 新增任务
    addReward () {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        const { expireDate, setting, ...other } = JSON.parse(JSON.stringify(this.form))
        if (['right_pkg', 'charge'].includes(this.form.type)) {
          setting.grant.unlimit = setting.grant.duration === 36792000 ? 1 : 0
        }
        const requestParam = { ...other,
          ...{
            // start_at: new Date(expireDate[0]) / 1000 || '',
            // stop_at: new Date(expireDate[1]) / 1000 || '',
            setting: JSON.stringify(setting)
          }
        }
        if (expireDate?.[0]) {
          requestParam['start_at'] = new Date(expireDate[0]) / 1000 || ''
          requestParam['stop_at'] = new Date(expireDate[1]) / 1000 || ''
        }
        delete requestParam.fileList

        if (this.form.id && this.editRow && (requestParam.total < this.editRow.total)) {
          this.msgError(`发放分数不能小于${this.editRow.total}`)
          return
        }
        const apiHandle = this.form.id ? updateReward : addReward

        apiHandle(requestParam).then(res => {
          this.msgSuccess(this.form.id ? '修改奖励成功' : '新增奖励成功')
          this.dialogVisible = false
          this.getTableList()
        })
      })
    },
    /** 删除按钮操作 */
    updateRewardStatus (row) {
      const id = row.id
      const { page: pageIndex, page_size: pageSize } = this.queryParams
      this.$confirm(`是否确认删除该奖品？奖品名：${row.name}`, '警告', {
        type: 'warning'
      }).then(() => {
        updateReward({ id, status: 'deleted' }).then(() => {
          this.queryParams.page = this.getCurrentPage({ total: this.total, pageSize, pageIndex })
          this.getTableList()
          this.msgSuccess(`删除成功`)
        })
      })
    },
    reset () {
      this.resetForm('form')
      this.form.setting = {
        alarm: {
          enable: 0,
          least: 5,
          robot: ''
        },
        grant: {
          quantity: 0,
          unit: '',
          unit_name: '',
          pkg_id: null,
          duration: null
        }
      }
    },
    onUpload ({ file, data = {} }) {
      const forms = new FormData()
      forms.append('file', file)
      uploadApi(forms).then(res => {
        const url = res.data?.url
        this.form.code_file = url
        this.form.fileList = [
          {
            name: file.name,
            url
          }
        ]
      })
    },
    beforeUpload (file) {
      if (file.type !== 'text/plain') {
        this.msgError('文件必须是txt格式')
        return false
      }
      if (file.size > 1024 * 1024 * 100) {
        this.msgError('文件大小不超过100M')
        return false
      }
      return true
    },
    onFileRemove () {
      this.form.code_file = ''
      this.form.fileList = []
    }
  },
  created () {
    this.getPackageRightList()
    this.handleQuery()
    this.memberTimeOptions = getMemberValidTime()
  }
}
</script>
<style lang="scss" scoped>
.pagination-wrap {
  padding: 20px 0;
}
.add-task-dialog {
  .unit {
    margin-left: 10px;
  }
  .el-col {
    .el-input-number--medium {
      width: 116px;
      margin: 0 4px;
    }
  }
}
.upload-demo {
  line-height: 16px;
}
</style>
